package com.gitee.liuzhi.framework.starter.response.handler;

import com.gitee.liuzhi.framework.starter.response.apiresult.DataResult;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Objects;

/**
 * Created by 2022/4/29/0029
 *
 * @author LiuZhi
 * @version V1.0
 * @description: 全局响应
 */
@RestControllerAdvice(annotations = {RestController.class})
public class ResponseHandler implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        //null表示该controller没有返回值
        if (Objects.isNull(body)) {
            return DataResult.success();
        }
        return DataResult.success(body);
    }

}


